<template>
    <view class="container">
        <!-- 步骤条 -->
        <view style="background-color: #fff;padding:20rpx">
            <u-steps :current="flow" active-color="#2979ff">
                <u-steps-item title="看视频"></u-steps-item>
                <u-steps-item title="考试"></u-steps-item>
                <u-steps-item title="完成"></u-steps-item>
            </u-steps>
        </view>

        <!-- 考试界面 -->
        <view v-if="flow === 1" class="exam-container">
            <!-- 题目区 -->
            <view style="display: flex;align-items: center;color: black;">
                <view style="flex: 1;display: flex;align-items: center;font-weight: bold;margin-left: 20rpx;">
                    <view>{{ current+1 }}</view>
                    <view>/</view>
                    <view>{{ questionNum }}题</view>
                </view>
                <view style="flex: 4;">
                    <u-line-progress :percentage="percentage" activeColor="#165DFF" :showText="false"></u-line-progress>
                </view>
                <view
                    style="flex: 1;display: flex;align-items: center;justify-content: space-around;font-weight: bold;">
                    <view>
                        <u-icon name="clock"></u-icon>
                    </view>
                    <view>
                        {{ formattedTime }}
                    </view>
                </view>
            </view>
            <view>
                <view class="content">
                    <view class="content_title" v-if="list[current] && list[current].questionType == 1">单选</view>
                    <view class="content_title" v-if="list[current] && list[current].questionType == 2">判断</view>
                    <view class="content_title" v-if="list[current] && list[current].questionType == 3">多选</view>
                    <view class="content_title" v-if="list[current] && list[current].questionType == 4">填空</view>
                    <view class="content_title" v-if="list[current] && list[current].questionType == 5">简答</view>
                    <view v-if="list[current] && list[current].questionType != 4" class="content_ti">{{
                list[current].questionName }}
                    </view>
                    <view v-if="list[current] && list[current].questionType == 4" class="content_ti">{{
                list[current].questionName.replaceAll('_', '_____') }}</view>
                </view>
                <view class="checked">
                    <u-checkbox-group v-model="list[current].radio" placement="column" @change="checkboxChange"
                        v-if="list[current] && list[current].questionType == 3">
                        <u-checkbox labelSize="18px" size="20px"
                            style="width: 100%;padding:40rpx 35rpx;box-sizing: border-box;border-bottom: 1rpx solid #C6C6C6;"
                            :style="index == 0 || index == 2 ? 'background-color: #fff;' : ''"
                            v-for="(item, index) in list[current].questionAnswerList" :key="index"
                            :label="item.questionAnswerName" :name="index"></u-checkbox>
                    </u-checkbox-group>
                    <u-radio-group v-model="list[current].radio" placement="column" @change="groupChange"
                        v-if="list[current] && list[current].questionType == 1 || list[current] && list[current].questionType == 2">
                        <u-radio labelSize="18px" size="20px"
                            style="width: 100%;padding:40rpx 35rpx;box-sizing: border-box;border-bottom: 1rpx solid #C6C6C6;"
                            v-for="(item, index) in list[current].questionAnswerList" :key="index"
                            :label="item.questionAnswerName" :name="index"></u-radio>
                    </u-radio-group>
                    <view v-if="list[current] && list[current].questionType == 5"
                        style="margin: 20px;overflow-y: scroll;">
                        <u--textarea height="300px" v-model="shortAnswer" placeholder="请输入答案" count
                            :maxlength="-1"></u--textarea>
                    </view>
                    <view v-if="list[current] && list[current].questionType == 4 && list[current]">
                        <view style="display: flex;flex-direction: column;margin: 20px;"
                            v-for="(item, index) in list[current].questionName.split('_').length - 1" :key="index">
                            <u--input placeholder="请输入内容" border="surround" v-model="gapFilling[index]"></u--input>
                        </view>
                    </view>
                </view>
            </view>
            <view class="btn">
                <view v-if="current >= 1">
                    <u-button class="custom-style" text="上一题" @click="prevClick" type="success"></u-button>
                </view>
                <view v-if="current == list.length - 1">
                    <u-button type="warning" text="完成" @click="onFinish" throttleTime="5000" :loading="submitLoading"
                        loadingMode="spinner" loadingText="打分中"></u-button>
                </view>
                <view v-else>
                    <u-button text="下一题" @click="btnClick" type="primary"></u-button>
                </view>
            </view>
        </view>
        <view v-if="flow === 2" class="exam-container">
            <u-row>
                <u-col span="12">
                    <view class="result-cell">
                        <view class="result-label">
                            培训内容：
                        </view>
                        <view class="result-value">
                            {{ result.trainName }}
                        </view>
                    </view>
                </u-col>
            </u-row>
            <u-row>
                <u-col span="12">
                    <view class="result-cell">
                        <view class="result-label">
                            正确题数：
                        </view>
                        <view class="result-value">
                            {{ result.correctNum }}题
                        </view>
                    </view>
                </u-col>
            </u-row>
            <u-row>
                <u-col span="12">
                    <view class="result-cell">
                        <view class="result-label">
                            错误题数：
                        </view>
                        <view class="result-value">
                            {{ result.errorNum }}题
                        </view>
                    </view>
                </u-col>
            </u-row>
            <u-row>
                <u-col span="12">
                    <view class="result-cell">
                        <view class="result-label">
                            成绩：
                        </view>
                        <view class="result-value">
                            {{ result.totalScore }}分
                        </view>
                    </view>
                </u-col>
            </u-row>
            <view style="display: flex;justify-content: center;align-items: center; padding: 40rpx;">
                <u--image :showLoading="true" :src="src" :fade="true" mode="widthFix" width="600rpx" height="600rpx"
                    duration="450"></u--image>
            </view>
            <view class="btn2">
                <view>
                    <u-button text="返回首页" @click="goHome" type="primary" shape="circle"></u-button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { getStudyQuestion, paperMarking } from '@/api/train/index.js'
export default {
    data() {
        return {
            percentage:0,
            flow: 1, // 控制步骤进度
            currentQuestionIndex: 0,
            selectedAnswer: null,
            score: 0,
            currentQuestion: 1,
            questionNum: 50, // 题目数量
            planExaminationId: '',
            safetyTrainingId: '',
            radiovalue1: '',
            checkboxValue1: [],
            // 基本案列数据
            list: [],
            current: 0, //当前是第几题,
            question: [],
            newresultArr: [],
            resultArr: [],
            shortAnswer: '',
            gapFilling: [],
            isShort: 0,
            roomId: 0,
            submitLoading: false,
            //考试结束时间
            remainingTime: 1800,
            timer: null,
            src: '/static/images/buhege.png',// 定时器实例
            totalDuration: 0, // 新增：考试总时长
            actualDuration: 0, // 新增：实际作答时间
            result: {
                totalScore: 0,
                isPass: 1,
                trainName: '',
                correctNum: 0,
                errorNum: 0,
            }
        }
    },
    computed: {
        // 新增计算属性格式化时间
        formattedTime() {
            const minutes = Math.floor(this.remainingTime / 60)
            const seconds = this.remainingTime % 60
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
        }
    },
    onLoad(options) {
        if (options.id) {
            this.planExaminationId = options.id;
            this.getList();
            this.startTimer() // 初始化后启动计时
        }
    },
    beforeDestroy() {
        clearInterval(this.timer) // 组件销毁时清除定时器
    },
    methods: {
        updateProgress() {
        this.percentage = ((this.current + 1) / this.questionNum * 100).toFixed(2);
    },
        goHome() {
            uni.reLaunch({
                url: '/pages/index'
            })
        },
        // 新增倒计时方法
        startTimer() {
            this.timer = setInterval(() => {
                if (this.remainingTime > 0) {
                    this.remainingTime--
                    this.actualDuration = this.totalDuration - this.remainingTime; // 计算实际耗时
                } else {
                    clearInterval(this.timer)
                    this.$msg('考试时间已到，将自动交卷')
                    this.onFinish()
                }
            }, 1000)
        },
        checkboxChange(n) {
            this.question = n;
        },
        groupChange(n) {
            console.log(n)
            this.radiovalue1 = n;
        },
        prevClick() {
            this.current = this.current - 1;
        },
        btnClick() {
            if (this.current >= this.list.length - 1) {
                return false;
            } else {
                // 保存答案的逻辑改为对象数组格式
                const currentQuestion = this.list[this.current];
                let answer = '';

                if (currentQuestion.questionType <= 3) {
                    if (currentQuestion.radio == undefined) {
                        this.$msg('请选择答案');
                        return;
                    }

                    if (currentQuestion.questionType == 3) { // 多选
                        answer = currentQuestion.radio
                            .map(index => currentQuestion.questionAnswerList[index].questionAnswerOption)
                            .join(',');
                    } else { // 单选/判断
                        answer = currentQuestion.questionAnswerList[currentQuestion.radio].questionAnswerOption;
                    }
                } else if (currentQuestion.questionType == 4) {
                    answer = this.gapFilling.join(',');
                } else if (currentQuestion.questionType == 5) {
                    answer = this.shortAnswer;
                }

                // 存储为 {questionId, chooseAnswer} 格式
                this.newresultArr[this.current] = {
                    questionId: currentQuestion.questionId,
                    chooseAnswer: answer
                };
                this.current++;
                this.updateProgress(); // 新增进度更新
            }
        },
        // 新增保存当前题目方法
        saveCurrentQuestion() {
            const currentQuestion = this.list[this.current];
            let answer = '';

            if (currentQuestion.questionType <= 3) {
                if (currentQuestion.radio == undefined) {
                    this.$msg('请选择答案');
                    return false;
                }

                if (currentQuestion.questionType == 3) { // 多选
                    answer = currentQuestion.radio
                        .map(index => currentQuestion.questionAnswerList[index].questionAnswerOption)
                        .join(',');
                } else { // 单选/判断
                    answer = currentQuestion.questionAnswerList[currentQuestion.radio].questionAnswerOption;
                }
            } else if (currentQuestion.questionType == 4) {
                answer = this.gapFilling.join(',');
            } else if (currentQuestion.questionType == 5) {
                answer = this.shortAnswer;
            }

            this.newresultArr[this.current] = {
                questionId: currentQuestion.questionId,
                chooseAnswer: answer
            };
            return true;
        },
        onFinish() {
            // 先保存当前题目
            if (!this.saveCurrentQuestion()) {
                return;
            }
            // 过滤未答题项并转换为数组
            const answerList = this.newresultArr.filter(item => item);
            paperMarking({
                planExaminationId: Number(this.planExaminationId),
                answerStr: JSON.stringify(answerList),
                duration: this.actualDuration // 新增耗时参数
            }).then(res => {
                console.log(res);
                this.showResult(res.data);
            });
        },

        showResult(data) {
            this.flow = 2; // 切换到考试结果界面
            this.result = data;
            if (data.isPass == 1) {
                this.src = '/static/images/hege.png';
            }else{
                this.src = '/static/images/buhege.png';
            }
        },
        async getList() {
            const { data, code, msg } = await getStudyQuestion({
                planExaminationId: this.planExaminationId,
            })
            if (code == 200) {
                this.list = data.questionList;
                this.questionNum = data.questionList.length;
                this.totalDuration = data.testDuration * 60; // 保存总时长
                this.remainingTime = this.totalDuration;
                this.updateProgress(); // 初始化进度
            }
        },

    }
}
</script>

<style lang="scss" scoped>
.exam-container {
    margin-top: 40rpx;
    padding-bottom: 140rpx;
    box-sizing: border-box;
}

/deep/ .u-checkbox-label--left {
    flex-direction: row;
    width: 100%;
    padding: 40rpx 35rpx;
    box-sizing: border-box;
    border-bottom: 1rpx solid #c6c6c6;
}

/deep/ .u-radio {
    display: flex;
    flex-direction: row;
    overflow: hidden;
    flex-direction: row;
    align-items: center;
    width: 100%;
    padding: 40rpx 35rpx;
    box-sizing: border-box;
    border-bottom: 1rpx solid #c6c6c6;
}

.content {
    padding: 35rpx;
    box-sizing: border-box;
    position: relative;
    background-color: #fff;
    margin-top: 40rpx;

    .content_title {
        width: 90rpx;
        height: 40rpx;
        border-radius: 50rpx;
        border: 2px solid #165DFF;
        font-size: 20rpx;
        font-weight: 400;
        color: #ffffff;
        text-align: center;
        line-height: 40rpx;
        color: #165DFF;
        position: absolute;
        left: 35rpx;
        top: 43rpx;
    }

    .content_ti {
        font-size: 33rpx;
        font-weight: 400;
        color: #333333;
        text-indent: 120rpx;
        line-height: 55rpx;
    }
}

.checked {
    display: flex;
    flex-direction: column;
    background-color: #fff;
}

.btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    padding: 20rpx 30rpx;
    background: #fff;
    box-shadow: 0 -4rpx 24rpx rgba(0, 0, 0, 0.06);
    display: flex;
    justify-content: space-between;
    align-items: center;
    z-index: 100;

    view {
        width: 45%;
        margin: 0;

        /deep/ .u-button {
            width: 100%;
            height: 80rpx;
            font-size: 32rpx;
        }
    }
}

.btn2 {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    padding: 20rpx 30rpx;
    background: #fff;
    box-shadow: 0 -4rpx 24rpx rgba(0, 0, 0, 0.06);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;

    view {
        width: 70%;
        margin: 0;

        /deep/ .u-button {
            width: 100%;
            height: 80rpx;
            font-size: 32rpx;
        }
    }
}

.result-cell {
    display: flex;
    align-items: center;
    margin: 20rpx;
}

.result-label {
    width: 140rpx;
    color: #727687;
}

.result-value {
    color: #1C213E;
    font-weight: bold;
}
</style>